package net.itst.schwarzerdaumen;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class PlantsListAdapter extends SimpleCursorAdapter {

    private final Context context;
    private final int layout;
    private int button = 0;
    private CharSequence buttonLabel = "";
    Button plant_button = null;

    public PlantsListAdapter(Context context, int layout, Cursor c,
	    String[] from, int[] to) {
	super(context, layout, c, from, to);
	this.context = context;
	this.layout = layout;
    }

    public void setButton(int btnRes) {
	this.button = btnRes;
    }

    public void setButtonLabel(CharSequence btnLabel) {
	this.buttonLabel = btnLabel;
    }

    public boolean hasButtonConfig() {
	return (this.buttonLabel.length() > 0 && this.button > 0);
    }

    @Override
    public View newView(Context context, Cursor curPlants, ViewGroup parent) {

	// Cursor curPlants = getCursor();
	final LayoutInflater inflater = LayoutInflater.from(context);
	View v = inflater.inflate(layout, null);

	ImageView plant_icon = (ImageView) v.findViewById(R.id.plant_icon);
	TextView plant_name = (TextView) v.findViewById(R.id.plant_name);
	TextView plant_status = (TextView) v.findViewById(R.id.plant_status);

	if (hasButtonConfig()) {
	    plant_button = (Button) v.findViewById(this.button);
	}

	return v;
    }

    @Override
    public void bindView(View v, Context context, Cursor curPlants) {

	int idColumn = curPlants.getColumnIndex(TablePlants.ID);
	int iconColumn = curPlants.getColumnIndex(TablePlants.IMAGE);
	int nameColumn = curPlants.getColumnIndex(TablePlants.NAME);
	int statusColumn = curPlants.getColumnIndex(TablePlants.WNEXT);

	ImageView plant_icon = (ImageView) v.findViewById(R.id.plant_icon);
	TextView plant_name = (TextView) v.findViewById(R.id.plant_name);
	TextView plant_status = (TextView) v.findViewById(R.id.plant_status);

	int id = curPlants.getInt(idColumn);
	String icon = curPlants.getString(iconColumn);
	String name = curPlants.getString(nameColumn);
	String status = curPlants.getString(statusColumn);

	plant_name.setText(name);
	plant_status.setText(status);

	if (hasButtonConfig()) {
	    plant_button.setText(this.buttonLabel);
	    plant_button.setTag(id);
	}

	if (icon == null || icon == "") {
	    plant_icon.setImageResource(R.drawable.placeholder_plant);
	} else {
	    Uri icon_uri = Uri.parse(icon);
	    plant_icon.setImageURI(icon_uri);
	}
    }

}
